//
//  HMNetworkTools.m
//  MyMicroBlog
//
//  Created by Apple on 16/9/26.
//  Copyright © 2016年 Apple. All rights reserved.
//

#import "HMNetworkTools.h"

@implementation HMNetworkTools

+(instancetype)sharedTools{
    static HMNetworkTools *tools;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[HMNetworkTools alloc]init];
        //添加可接受类型
        tools.responseSerializer.acceptableContentTypes = [tools.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        tools.responseSerializer.acceptableContentTypes = [tools.responseSerializer.acceptableContentTypes setByAddingObject:@"text/plain"];
    });
    return tools;
}

-(void)requestWithType:(requestType)type andUrl:(NSString *)url andParams:(id)params andCallBack:(void (^)(id, NSError *))callBack{
    if (type == GET) {
        [self GET:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            callBack(nil,error);
        }];
    } else {
        [self POST:url parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            callBack(responseObject,nil);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            callBack(nil,error);
        }];
    }
}

@end


@implementation HMNetworkTools (Request)

-(void)requestAccessTokenWithCode:(NSString *)code andCallBack:(void (^)(id,NSError *))callBack{
    //请求接口地址
    NSString *url = @"https://api.weibo.com/oauth2/access_token";
    //定义参数
    NSArray <NSDictionary *>*params = @[
                                        @{@"client_id" : WeiBoAppKey},
                                        @{@"client_secret" :  WeiboAppSecret},
                                        @{@"grant_type" : @"authorization_code"},
                                        @{@"code" : code},
                                        @{@"redirect_uri" : WeiBoRedirect_URI}
                                        ];
    //发送请求
    [self requestWithType:POST andUrl:url andParams:params andCallBack:callBack];
}


@end
